//
//  ViewController.swift
//  TouchEvent
//
//  Created by 移云 on 2020/5/11.
//  Copyright © 2020 MaoYeYeDeJiangCuCha. All rights reserved.
//

import UIKit
//单点触控
class ViewController: UIViewController {

    var redView = SingleTouchView.init(frame: CGRect.init(x: 100, y: 100, width: 200, height: 200));
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        self.view.addSubview(redView);
        
    }
    
    //点击屏幕 让方块的中心移动到点击的地方
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch:AnyObject in touches {
            let t:UITouch = touch as! UITouch
            //当在屏幕上连续拍动两下时，背景回复为白色
            if t.tapCount == 2{
                self.view.backgroundColor = UIColor.gray
            }else if t.tapCount == 1{
                self.view.backgroundColor = UIColor.white
            }
//            移动手指 让方块的跟随移动
//             redView.center = t.location(in: self.view)
        }
        
    }
    
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        for touch:AnyObject in touches {
            let t:UITouch = touch as! UITouch
            //移动手指 让方块的跟随移动
//             redView.center = t.location(in: self.view)
            
            //移动手指 让方块根据偏移量移动
            let p = t.location(in: t.view)
            let lastP = t.previousLocation(in: t.view)
            
            //偏移量
            let offsetX = p.x - lastP.x
            let offsetY = p.y - lastP.y
            //让方块的中心在自身的基础上加上偏移量
            redView.center = CGPoint.init(x: redView.center.x + offsetX, y: redView.center.y + offsetY)
            
        }
        
        
    }
    


}

